const __root__ = process.cwd()
const path = require('path')
const {
	mongodbConf,
} = require(path.join(__root__, 'server', 'config', 'sysConf.json'))

const {
	ObjectID,
	MongoClient,
} = require('mongodb')

const _dbConnectPro = MongoClient.connect(mongodbConf.url)

/**
 * 判决集合及相关索引是否存在
 * 不存在则创建并创建相关索引
 * @param  {string} colName      	集合名称
 * @param  {Array} indexArr 		集合索引
 *         indexArr数组中的为string/object类型
 *         object = {
 *         		name:'', 索引名称
 *         		opts:{}  索引可选项,参照mongodb createIndex API
 *         }
 * 
 * @return {Promise}
 */
module.exports = async function(colName, indexArr) {
	let db = await _dbConnectPro
	let colArr = await db.listCollections({
		name: colName,
	}).toArray()
	let collection = db.collection(colName)

	// 判断该集合(collection)是否存在
	if (colArr.length < 1) {
		collection = await db.createCollection(colName)
	}

	if (!Array.isArray(indexArr) || indexArr.length < 1)
		return collection

	/**
	 * 创建索引
	 * @param  {string} colName      	集合名称
	 * @param  {Array} indexArr 		集合索引
	 *         indexArr数组中的为string/object类型
	 *         object = {
	 *         		name:'', 索引名称
	 *         		opts:{}  索引可选项,参照mongodb createIndex API
	 *         }
	 * 
	 * @return {Promise}         		[description]
	 */
	for (let i = 0; i < indexArr.length; i++) {
		let index = indexArr[i]
		let uuidIndex = await collection.indexExists(index.name || index)
		if (!uuidIndex) {
			let name = index.name || index
			let opts = index.opts || {}
			opts.name = opts.name || name
			collection.createIndex(name, opts)
		}
	}
	return collection
}